<template>
  <div class="upload-invoice-box">
    <tabs
      is-new-tabs
      :tabs-arr="deliverGoodsTabsArr"
      @returnIndex="tabsHandle" />
    <div class="big-upload-box">
      <p class="title">上传文件</p>
      <div
        class="invoice-upload-box"
        v-loading="upLoadLoading"
        v-if="isShowModel === 1">
        <!-- 本地上传 -->
        <el-upload
          action="string"
          :show-file-list="false"
          :accept="imageLimit"
          :http-request="toRequest"
          fit="scale-down"
        >
          <div class="upload-box">
            <div class="upload">
              <el-image
                style="width: 20px; height: 20px;"
                :src="uploadImg" />
              <p>上传附件</p>
            </div>
            <p class="upload-tips">支持JPEG、PNG、PDF文件,不超过20MB</p>
          </div>
        </el-upload>
        <!-- 手机上传 -->
        <div class="m-upload">
          <auto-upload
            action="fileUpload"
            :m-props="{urlObj:qrcodeImg,urlStr:'url'}"
          />
          <!-- <m-upload
            action="fileUpload"
            :m-props="{urlObj:qrcodeImg,urlStr:'url'}"
          /> -->
        </div>
      </div>
      <!-- 展示上传的图片和提示信息 -->
      <div
        v-if="isShowModel === 2"
        style="margin-top:30px;"
        v-viewer>
        <el-image
          style="width: 266px; height: 189px;"
          :src="isPdf ? pdfImg : invoiceUrl"
          fit="cover" />
        <p class="tips-info">
          <el-image
            style="width: 14px; height: 14px; margin: 0 10px;"
            :src="tipsImg"
            fit="cover" />正在获取发票信息，请耐心等待…系统即将返回结果
        </p>
      </div>
      <!-- 手动录入信息 / OCR识别返回的信息对比 -->
      <div
        class="form-list-box"
        v-if="isShowModel === 3 || isShowModel === 4">
        <p/>
        <el-form
          :model="FormData"
          :rules="formRules"
          ref="FormData"
          label-width="110px"
          class="demo-FormData"
        >
          <el-form-item
            label="历史上传"
            prop="historyUpload"
            v-if="isShowModel !== 3">
            <el-select
              filterable
              remote
              reserve-keyword
              v-model="FormData.historyUpload"
              :remote-method="remoteMethod"
              @change="getHistoryVal"
              placeholder="请选择"
              :disabled="isDisabled">
              <el-option
                v-for="item in historyInvoiceList"
                :key="item.id"
                :label="item.label"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="发票号码"
            prop="quantity">
            <el-input
              v-model="FormData.quantity"
              :disabled="isDisabled"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="发票代码"
            prop="invoiceCode">
            <el-input
              v-model="FormData.invoiceCode"
              :disabled="isDisabled"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="开票日期"
            prop="invoiceDate">
            <el-date-picker
              :disabled="isDisabled"
              value-format="yyyy-MM-dd"
              v-model="FormData.invoiceDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item
            label="检验码后六位"
            prop="checkCode">
            <el-input
              v-model="FormData.checkCode"
              :disabled="isDisabled"
              placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="合计金额(元)"
            prop="totalAmount">
            <!-- <el-input v-model="FormData.totalAmount"></el-input> -->
            <el-input-number
              placeholder="请输入"
              :disabled="isDisabled"
              :controls="false"
              v-model="FormData.totalAmount"
              :precision="3"
              :max="9999999999999.999"
            />
          </el-form-item>
        </el-form>
        <p
          v-if="tipsInfo"
          class="tips-info"
        >
          <el-image
            style="width: 14px; height: 14px; margin: 0 10px;"
            :src="tipsImg"
            fit="cover" />
          {{ tipsInfo }}
        </p>
      </div>
    </div>
    <div
      class="footer-box"
      v-if="isShowModel === 3 || isShowModel === 4">
      <el-button
        type="primary"
        :disabled="isDisabled"
        @click="toSubmitForm"
      >{{ isShowModel === 3 ? '确定一致，去验证真伪' : '确定' }}</el-button>
      <el-button
        @click="resetForm"
        v-if=" isShowModel === 4"
        :disabled="isDisabled">取消</el-button>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="isTruthTestResult"
      width="500px"
      :before-close="handleClose"
      class="truth-test-result-box"
    >
      <p>
        <i :class="truthTestResultIcon"/><span>{{ truthTestResultInfo }}</span>
      </p>
      <span
        slot="footer"
        class="dialog-footer">
        <el-button
          type="primary"
          @click="toKnow">我知道了</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import tabs from '@components/tabs/index.vue'
import AutoUpload from '@components/auto-upload'
import { fileUpload } from '@const/api.js'
import { hasIn } from 'lodash'
import { distinguishForOCR, historyInvoiceList, saveInvoiceElement, confirmInvoice } from '@const/beforeSettleApi.js'

export default {
  components: { tabs, AutoUpload },
  data () {
    return {
      uploadImg: require('@assets/icon/beforeSettle/upload.png'),
      tipsImg: require('@assets/icon/beforeSettle/tips.png'),
      pdfImg: require('@assets/img/pdf.png'),
      tabIndex: 0,
      deliverGoodsTabsArr: [
        { lab: '上传发票影像', val: 0, badge: { value: null } },
        { lab: '录入发票信息', val: 1, badge: { value: null } }
      ],
      upLoadLoading: false,
      imageLimit: '.jpeg, .jpg, .png, .pdf',
      typeList: ['png', 'jpeg', 'jpg', 'PNG', 'JPEG', 'JPG', 'pdf'],
      invoiceUrl: '', // 上传的发票url
      qrcodeImg: {
        url: ''
      },

      FormData: { // 表单数据
        historyUpload: '',
        quantity: '',
        invoiceCode: '',
        invoiceDate: '',
        checkCode: ''
        // totalAmount: ''
      },
      formRules: {
        quantity: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 64, message: '请输入1-64个字符', trigger: 'blur' }
        ],
        invoiceCode: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 64, message: '请输入1-64个字符', trigger: 'blur' }
        ],
        invoiceDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        checkCode: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 126, message: '请输入1-126个字符', trigger: 'blur' }
        ],
        totalAmount: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      infoOCR: false, // ocr是否返回信息
      tipsInfo: '',
      isDisabled: false, // 是否禁用
      isTruthTestResult: false, // 验证返回结果显示
      truthTestResultIcon: '',
      truthTestResultInfo: '',

      historyInvoiceList: [] // 历史数据
    }
  },
  computed: {
    isShowModel () {
      let val = 1
      if (!this.invoiceUrl && this.tabIndex === 0) {
        //   第一个tab，没有图片
        val = 1
      } else if (this.invoiceUrl && this.tabIndex === 0 && !this.infoOCR) {
        //   第一个tab，有图片，正在获取数据
        val = 2
        this.disabledTab(true)// tab禁用
      } else if (this.invoiceUrl && this.tabIndex === 0 && this.infoOCR) {
        //   第一个tab，有图片,获取到发票数据（展示表单，去掉历史发票字段，下边按钮是“去验真伪”）
        val = 3
        this.disabledTab(true)// tab禁用
      } else if (this.tabIndex === 1) {
        //   第二个tab
        val = 4
      }
      return val
    },
    isPdf () {
      return /\.pdf$/.test(this.invoiceUrl)
    }
  },
  watch: {
    'qrcodeImg.url' (val) {
      if (!val) return
      // 校验图片格式
      let type = val.substring(val.lastIndexOf('.') + 1)
      let isImage = this.typeList.includes(type)
      if (!isImage) {
        this.$message.error('上传文件只能是PNG、JPEG、PDF格式!')
        return false
      }

      this.invoiceUrl = val
      this.qrcodeImg.url = ''
      this.OCRidentifyInvoice(this.invoiceUrl)
    }
  },
  mounted () {
    this.remoteMethod('')
    this.initNavButtons()
  },
  methods: {
    // 初始化 导航栏 按钮组
    initNavButtons () {
      let state = Number(this.$route.query.authState)
      let obj = {
        type: 'btn',
        arr: [
          {
            val: '返回',
            handle: this.goBack,
            disabled: this.isDisabled
          }
        ]
      }
      this.$store.commit('changeLayoutHandle', obj)
    },
    goBack () {
      this.$router.go(-1)
    },
    // 选择历史发票，回填数据
    getHistoryVal (val) {
      this.historyInvoiceList.forEach(item => {
        if (item.id === val) {
          this.FormData.quantity = item.invoiceNo
          this.FormData.invoiceCode = item.invoiceCode
          this.FormData.invoiceDate = item.invoiceDate
          this.FormData.checkCode = item.checkCode
          this.FormData.totalAmount = item.totalPriceTax
        }
      })
    },
    // 查询历史发票池
    remoteMethod (val) {
      this.$axios({
        method: 'get',
        url: historyInvoiceList,
        params: {
          invoiceNo: val
        }
      })
        .then(res => {
          this.historyInvoiceList = res.data.payload || []
          this.historyInvoiceList.forEach(item => {
            item.label = item.invoiceNo + ' 可关联金额（元）' + (item.canRelevanceAmount ? item.canRelevanceAmount.toFixed(3) : 0.000)
          })
        })
    },
    // 关闭验证返回的结果弹框
    handleClose () {},
    //   tab禁用
    disabledTab (data) {
      this.deliverGoodsTabsArr[0].disabled = data
      this.deliverGoodsTabsArr[1].disabled = data
      // this.tipsInfo = 1
      if (this.invoiceUrl && this.tabIndex === 0 && this.infoOCR) {
        this.tipsInfo = '请确认以上信息是否与发票一致，如不一致请进行更正'
      }
    },
    //   确定提交后，form不可在编辑
    toSubmitForm () {
      // 先校验是否有空
      this.$refs.FormData.validate(valid => {
        if (valid) {
          if (this.tabIndex === 1) {
            this.disabledTab(true) // tab禁用
            this.tipsInfo = '正在获取发票信息，请耐心等候…系统即将返回结果'
          } else {
            this.tipsInfo = '正在验证发票真伪，请耐心等候…系统即将返回结果'
          }
          this.isDisabled = true // 表单禁用
          this.initNavButtons()

          let data = {
            checkCode: this.FormData.checkCode, // 校验码
            invoiceCode: this.FormData.invoiceCode, // 发票代码
            invoiceDate: this.FormData.invoiceDate, // 开票日期
            invoiceNo: this.FormData.quantity, // 发票号
            totalPriceTax: this.FormData.totalAmount, // 总金额

            invoiceUrl: this.invoiceUrl, // 发票url
            // sourceType: 0,//已关联发票列表 上传影像后校验0 (T平台过来的数据1)
            ...this.$route.query,
            saleOrderId: this.$route.query.id // 主单id
          }
          this.$axios({
            method: 'post',
            url: saveInvoiceElement,
            data: data
          })
            .then(res => {
              if (res.data.payload.exsit === '2') {
                this.$router.go(-1)
              } else {
                if (res.data.payload.msg) {
                  this.isTruthTestResult = true
                  this.truthTestResultIcon = 'el-icon-circle-check'
                  this.truthTestResultInfo = res.data.payload.msg
                } else {
                  this.verifyAuthenticity(data) // 验证发票真伪
                }
              }
            })
            .catch(() => {
              this.isDisabled = false
              this.initNavButtons()
              this.disabledTab(false)
              this.tipsInfo = '请确认以上信息是否与发票一致，如不一致请进行更正'
            })
        }
      })
    },
    // 校验真伪
    verifyAuthenticity (data) {
      this.$axios({
        method: 'post',
        url: confirmInvoice,
        data: data
      })
        .then(res => {
          if (res.data.code === '0') {
            this.isTruthTestResult = true
            let status = Object.keys(res.data.payload)[0]
            let arr = ['el-icon-circle-check', 'el-icon-circle-close']
            this.truthTestResultIcon = arr[status]
            this.truthTestResultInfo = res.data.payload[status]
          }
        })
        .catch(() => {
          this.isDisabled = false
          this.initNavButtons()
          this.disabledTab(false)
          this.tipsInfo = '请确认以上信息是否与发票一致，如不一致请进行更正'
        })
    },
    // 我知道了
    toKnow () {
      if (this.truthTestResultInfo === '验真通过') {
        this.$router.go(-1)
      } else {
        this.isDisabled = false
        this.initNavButtons()
        this.disabledTab(false)
      }

      this.isTruthTestResult = false
    },
    //   表单重置一下
    resetForm () {
      this.$refs.FormData.resetFields()
    },
    // tabs切换处理事件
    tabsHandle (index) {
      this.invoiceUrl = ''
      this.tabIndex = index
      if (index === 1) {
        // tab切换重置表单数据
        this.FormData = {
          historyUpload: '',
          quantity: '',
          invoiceCode: '',
          invoiceDate: '',
          checkCode: ''
          // totalAmount: ''
        }
        // 手动录入的金额非必填
        this.formRules.totalAmount = []
      } else {
        // OCR识别的金额必填
        this.formRules.totalAmount = [{ required: true, message: '请输入', trigger: 'blur' }]
      }
      this.tipsInfo = ''
    },
    // 上传文件
    toRequest (data) {
      // 图片拦截
      let FileType = data.file.name.split('.')

      const isImage = this.typeList.includes(FileType[1])
      if (!isImage) {
        this.$message.error('上传文件只能是PNG、JPEG格式!')
        return false
      }
      const isNumM = data.file.size / 1024 / 1024 < 20
      if (!isNumM) {
        this.$message.error('上传文件大小不能超过 20MB!')
        return false
      }
      this.upLoadLoading = true
      // 发起请求
      let fd = new FormData()
      fd.append('file', data.file)
      this.$axios({
        method: 'post',
        url: fileUpload,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd
      }).then(res => {
        this.$message({ type: 'success', message: '上传成功' })
        // 赋值上传后的地址给文档
        this.invoiceUrl = res.data.payload
        this.OCRidentifyInvoice(res.data.payload)
        this.upLoadLoading = false

        // this.infoOCR = true // OCR返回了发票数据
        // this.FormData = {
        //   quantity: '1',
        //   invoiceCode: '1',
        //   invoiceDate: '2020-6-18',
        //   checkCode: '1',
        //   totalAmount: '1'
        // }
        // this.imagesurlstr = res.data.payload
        // this.$emit('ReturnImgUrl', this.imagesurlstr, this.key)
      })
    },
    // OCR识别发票
    OCRidentifyInvoice (url) {
      this.$axios({
        method: 'post',
        url: distinguishForOCR,
        data: {
          imgUrl: url
        }
      })
        .then(res => {
          if (res.data.code !== '0') return
          const resData = hasIn(res, 'data.payload') ? res.data.payload : {}
          if (typeof resData === 'string') {
            this.$message.warning('请上传真实发票')
            this.invoiceUrl = ''
            return
          }
          this.infoOCR = true // OCR返回了发票数据
          this.FormData = res.data.payload
        })
        .catch(() => {
          this.invoiceUrl = ''
          this.initNavButtons()
          this.disabledTab(false)
        })
    }
  }
}
</script>
<style lang="less">
.upload-invoice-box {
  padding: 0 !important;
  position: relative;
  // .tab-list-box {
  //   border-bottom: 10px solid #f7f8fa;
  //   padding: 30px 10px 20px 10px !important;
  // }
  .big-upload-box {
    padding: 0 10px;
    .title {
      line-height: 52px;
      font-size: 16px;
      font-weight: bold;
      border-bottom: 1px solid #e9e9e9;
    }
    .invoice-upload-box {
      display: flex;
      padding: 30px 0;
      position: relative;
      .upload-box {
        .upload {
          width: 158px;
          height: 53px;
          border: 1px solid #e8e8e8;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          color: #9ca6c7;
          p {
            margin-left: 10px;
          }
        }
        .upload-tips {
          font-size: 14px;
          color: #9ca6c7;
          margin-top: 20px;
          text-align: left;
        }
      }
      //   手机二维码样式
      /deep/.m-upload {
        position: absolute;
        top: 20px;
        left: 220px;
        .el-button--primary {
          color: #2371c5;
          background: #fff;
          border-radius: 0;
          border: 1px solid #2371c5;
          font-size: 20px;
          padding: 0;
        }
        .qrcode_upload_box .icon-qrcode {
          font-size: 50px;
        }
      }
    }
    // 提示信息样式
    .tips-info {
      margin-top: 30px;
      background: #e6f7ff;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      width: 475px;
      height: 40px;
      border: 1px solid #2371c5;
      border-radius: 5px;
      display: flex;
      align-items: center;
    }
    //   表单样式
    .form-list-box {
      width: 540px;
      margin: 0 auto;
      margin-top: 30px;
      .el-input-number--medium {
        width: 428px;
      }
      .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: 428px;
      }
      .el-select {
        width: 428px;
      }
      .tips-info {
        margin-top: 40px;
        float: right;
      }
    }
  }
  .footer-box {
    width: 100%;
    background: #fff;
    position: fixed;
    left: 0;
    bottom: 0;
    border-top: 1px solid #e8e8e8;
    padding: 20px;
    display: flex;
    justify-content: flex-end;
    // margin-top: 200px;
  }

  //   tab样式
  .custom-tabs-box .tabs-item .item-border {
    margin-top: 10px !important;
    width: 130px;
  }
  .custom-tabs-box .tabs-item {
    padding: 0;
  }
  //   验真结果弹框
  .truth-test-result-box {
    p {
      display: flex;
      align-items: center;
      i {
        font-size: 20px;
        margin: 10px;
        color: #67c23a;
      }
    }
    p:last-child i {
      color: #f56c6c;
    }
  }
}
.el-input-number.is-without-controls .el-input__inner {
  text-align: left;
}
</style>
